package com.imonsoft.common.util.upload;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.imonsoft.common.util.ContextUtil;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.common.util.FileUtil;
import com.imonsoft.common.util.ImageUtil;
import com.imonsoft.common.util.MD5Util;

/**
 * 图片上传处理类
 * 
 * @author LiQianHui
 * @date 2011-12-18
 * @version 2011
 */
public class ImageUploadUtil {

	protected final static Log logger = LogFactory.getLog(ImageUploadUtil.class);

	/**
	 * 上传图片代码 如imageUpload(mFile,4,{ { 100, 100 } })
	 * 
	 * @param mFile
	 * @param filePath
	 * @param size
	 *            上传图片的规格seze[<100,100>,<200,200>]等形式， 系统自动帮你转换相应规格的图片
	 *            注意根据需要才取，不然会导致服务器负担 int aa[][] ={{100,100},{200,200}}; String
	 *            url = ImageUploadUtil.imageUpload(mFile,4,aa);
	 * 活动海报：{528,468} 商家LOGO：{500,350} 晒单预览：{100,100}
	 * @see ClaimController
	 * @return
	 */
	public static String imageUpload(MultipartFile mFile, final int[][] seze) {
		Assert.notNull(mFile, "上传的文件不能为空");
		ContextUtil.setFlashMessage("操作成功！");
		String webPath = FileUtil.getRealPath();

		String fileName = mFile.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));// 后缀名

		String subPath = DateUtil.getNowDate("yyyy/MM/dd");
		String saveFileName = MD5Util.encode(UUID.randomUUID().toString());// 唯一名称
		fileName = saveFileName + suffix;
		String savepath = webPath + UpFileUtil.USERFILE + subPath;
		/**
		 * 读取IO写入到文件夹下面
		 */
		InputStream is = null;
		// 保存路径
		String fileURL = savepath + "/" + fileName;
		try {
			// 获得输入流
			is = mFile.getInputStream();
			FileUtil.save(is, savepath, fileName);
			if (seze != null) {
				for (int[] aa : seze) {
					String newFileURL = fileURL + "_" + aa[0] + "X" + aa[1] + suffix;
					ImageUtil.imageResize(fileURL, newFileURL, aa[0]);
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage());
			ContextUtil.setFlashMessage("错误:" + e.getMessage());
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
					ContextUtil.setFlashMessage("错误:" + e.getMessage());
				}
			}
		}
		String returnPath = fileURL.replace(webPath, "");
		return returnPath;
	}
}
